<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import { getStockInListApi, putStockInDeleteApi } from '@/api/Buy'

// mock数据
let sourceData = ref(["销售订单", "库存备货", "其他"]);
let stateData = ref(["未分解", "已分解", "已完成", "已关闭", "已撤回"]);
let allData = ref([]); // 存储所有数据
let tableData = ref([]); // 存储当前页数据
let currentPage = ref(1);
let pageSize = ref(10);
let total = ref(0);
let showDatePicker = ref(false);
let loading = ref(false); // 加载状态
const $router = useRouter();

// 查询参数
const queryParams = ref({
  keyword: '',         // 入库单号/名称
  batchNo: '',        // 批次号
  stockInDate: '',    // 入库时间
  inspectionNo: '',   // 来料检验单编号
  productionDate: '', // 生产日期
  expiryDate: ''      // 到期日期
})

// 计算过滤后的数据
const filteredData = computed(() => {
  return allData.value.filter(item => {
    const keywordMatch = !queryParams.value.keyword || 
      (item.name && item.name.includes(queryParams.value.keyword)) || 
      (item.stockInNo && item.stockInNo.includes(queryParams.value.keyword));
    
    const batchNoMatch = !queryParams.value.batchNo || 
      (item.batchNo && item.batchNo.includes(queryParams.value.batchNo));
    
    const stockInDateMatch = !queryParams.value.stockInDate || 
      (item.stockInDate && item.stockInDate === queryParams.value.stockInDate);
    
    const inspectionNoMatch = !queryParams.value.inspectionNo || 
      (item.inspectionNo && item.inspectionNo.includes(queryParams.value.inspectionNo));
    
    const productionDateMatch = !queryParams.value.productionDate || 
      (item.productionDate && item.productionDate === queryParams.value.productionDate);
    
    const expiryDateMatch = !queryParams.value.expiryDate || 
      (item.expiryDate && item.expiryDate === queryParams.value.expiryDate);
    
    return keywordMatch && batchNoMatch && stockInDateMatch && 
           inspectionNoMatch && productionDateMatch && expiryDateMatch;
  });
});

// 获取入库单列表
const fetchStockInList = async () => {
  try {
    loading.value = true;
    const response = await getStockInListApi();
    allData.value = response.results || [];
    total.value = allData.value.length;
    updateTableData();
  } catch (error) {
    console.error('获取入库单列表失败:', error);
    allData.value = [];
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
}

// 更新表格数据（分页+过滤）
const updateTableData = () => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  tableData.value = filteredData.value.slice(start, end);
}

// 分页变化
const handler = (page) => {
  currentPage.value = page;
  updateTableData();
};

// 每页条数变化
const sizeHandler = (page_size) => {
  pageSize.value = page_size;
  currentPage.value = 1; // 重置到第一页
  updateTableData();
};

// 查询按钮
const handleSearch = () => {
  currentPage.value = 1; // 重置为第一页
  updateTableData();
};

//删除操作
const handleDelete = (id) => {
  console.log(id);
  putStockInDeleteApi(id).then(() => {
    fetchStockInList();
  }).catch((error) => {
    console.error('删除入库单失败:', error);
  });
};

//编辑操作
const handleEdit = (id) => {
  $router.push(`/storage/entrance/editBuy/${id}`);
};

// 重置查询
const handleReset = () => {
  queryParams.value = {
    keyword: '',
    batchNo: '',
    stockInDate: '',
    inspectionNo: '',
    productionDate: '',
    expiryDate: ''
  };
  handleSearch();
};

// 路由跳转
const gotoAdd = () => {
  $router.push("/storage/entrance/addBuy");
};

const gotoDetail = (id) => {
  $router.push(`/storage/entrance/buyDetail/${id}`);
};

// 初始化获取数据
onMounted(() => {
  fetchStockInList();
});
</script>

<template>
  <div style="padding: 20px">
    <el-card>
      <div class="operateContainer">
        <div class="formContainer" :style="showDatePicker ? 'height:85px' : 'height:32px'">
          <el-form inline>
            <el-form-item>
              <el-input v-model="queryParams.keyword" placeholder="请输入入库单号/名称" style="width: 250px"
                clearable></el-input>
            </el-form-item>
            <el-form-item>
              <el-input v-model="queryParams.batchNo" placeholder="请输入批次号" style="width: 250px" clearable></el-input>
            </el-form-item>
            <el-form-item>
              <el-date-picker v-model="queryParams.stockInDate" style="width: 250px" type="date" placeholder="请选择入库时间"
                value-format="YYYY-MM-DD" clearable></el-date-picker>
            </el-form-item>
            <div style="margin-top: 20px" v-show="showDatePicker">
              <el-form-item>
                <el-input v-model="queryParams.inspectionNo" placeholder="请输入来料检验单编号/名称" style="width: 250px"
                  clearable></el-input>
              </el-form-item>
              <el-form-item>
                <el-date-picker v-model="queryParams.productionDate" style="width: 250px" type="date"
                  placeholder="请选择生产日期" value-format="YYYY-MM-DD" clearable></el-date-picker>
              </el-form-item>
              <el-form-item>
                <el-date-picker v-model="queryParams.expiryDate" style="width: 250px" type="date" placeholder="请选择到期日期"
                  value-format="YYYY-MM-DD" clearable></el-date-picker>
              </el-form-item>
            </div>
          </el-form>
        </div>
        <div class="searchOperate">
          <div class="button">
            <el-button type="primary" plain style="width: 80px" @click="handleReset">重置</el-button>
            <el-button type="primary" style="width: 80px" @click="handleSearch">查询</el-button>
          </div>
          <div class="more">
            <el-button type="primary" link @click="showDatePicker = !showDatePicker">更多</el-button>
            <el-icon color="#1B9AEE" :class="{ 'rotate-180': showDatePicker }">
              <CaretBottom />
            </el-icon>
          </div>
        </div>
      </div>
    </el-card>
    <el-card style="margin-top: 20px">
      <template #header>
        <span style="font-weight: bold">采购入库</span>
      </template>
      <div class="operate">
        <el-button style="width: 80px" type="primary" @click="gotoAdd">新增</el-button>
        <el-button style="width: 80px" type="primary" plain>导出</el-button>
      </div>
      <el-table :data="tableData" style="margin-top: 15px" border v-loading="loading">
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column align="center" label="序号" type="index" width="60" fixed="left"></el-table-column>
        <el-table-column align="center" label="入库单名称" fixed="left" width="100" prop="name">
          <template #default="{ row }">
            <el-button link type="primary" @click="gotoDetail(row.objectId)">{{ row.name }}</el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" label="入库单编号" prop="stockInNo" width="100"></el-table-column>
        <el-table-column align="center" label="入库日期" prop="stockInDate" width="90"></el-table-column>
        <el-table-column align="center" label="采购单名称" prop="purchaseOrderName" width="100"></el-table-column>
        <el-table-column align="center" label="采购单号" prop="purchaseOrderNo" width="90"></el-table-column>
        <el-table-column align="center" label="来料检验名称" prop="inspectionName" width="110"></el-table-column>
        <el-table-column align="center" label="来料检验单号" prop="inspectionNo" width="110"></el-table-column>
        <el-table-column align="center" label="物料名称" prop="materialName" width="90"></el-table-column>
        <el-table-column align="center" label="物料编号" prop="materialNo" width="90"></el-table-column>
        <el-table-column align="center" label="规格型号" prop="specification" width="90"></el-table-column>
        <el-table-column align="center" label="单位" prop="unit"></el-table-column>
        <el-table-column align="center" label="生产日期" prop="productionDate" width="90"></el-table-column>
        <el-table-column align="center" label="到期日期" prop="expiryDate" width="90"></el-table-column>
        <el-table-column align="center" label="批次号" prop="batchNo"></el-table-column>
        <el-table-column align="center" label="入库数量" prop="stockInQuantity" width="90"></el-table-column>
        <el-table-column align="center" label="仓库名称" prop="warehouseName" width="90"></el-table-column>
        <el-table-column align="center" label="库区名称" prop="zoneName" width="90"></el-table-column>
        <el-table-column align="center" label="库位名称" prop="locationName" width="90"></el-table-column>
        <el-table-column align="center" label="仓库负责人" prop="warehouseManager" width="100"></el-table-column>
        <el-table-column align="center" label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <!-- <el-button link type="primary" @click="handleStockIn(row)">
              入库
            </el-button> -->
            <el-button link type="primary" @click="handleEdit(row.objectId)">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(row.objectId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
        :background="true" layout="prev,pager,next,jumper,->,sizes,total" :total="total" @current-change="handler"
        @size-change="sizeHandler" style="margin-top: 10px"></el-pagination>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
/* 保持原有样式不变 */
.operateContainer {
  display: flex;
  align-content: center;
  justify-content: space-between;

  .formContainer {
    width: 1060px;
    height: 32px;
    transition: height 0.3s ease;
    overflow: hidden;

    .el-form-item {
      margin-bottom: 0;
    }
  }

  .searchOperate {
    display: flex;
    align-items: center;

    .more {
      margin-left: 20px;
      display: flex;
      align-items: center;
    }
  }
}

.rotate-180 {
  transition: transform 0.3s ease;
  transform: rotate(180deg);
}
</style>